<template>
  <n-card :bordered="false" class="antired-container card-container">
    <template #header>
      <n-input v-if="antiRedTable.checkedRowKeys.length === 0" class="w-80" placeholder="支持源网址、备注、短链查询"
               size="large">
        <template #prefix>
          <img :src="`${mainStore.commonImagePath}/icon_search.svg`" alt="icon_search">
        </template>
      </n-input>
      <n-space v-else :item-style="{height: '32px'}" align="center">
        <n-tag :bordered="false" class="text-base bg-transparent" type="primary">
          已选择 {{ antiRedTable.checkedRowKeys.length }} 条
        </n-tag>
        <n-tag :bordered="false" class="text-base cursor-pointer bg-transparent hover:bg-[#F7F9FFFF]">
          <template #avatar>
            <img :src="`${currentPageImagePath}/icon_qrcode_download.svg`" alt="icon_qrcode_download" width="24"/>
          </template>
          下载二维码
        </n-tag>
        <n-tag :bordered="false" class="text-base cursor-pointer bg-transparent hover:bg-[#F7F9FFFF]">
          <template #avatar>
            <img :src="`${currentPageImagePath}/icon_forms_download.svg`" alt="icon_forms_download" width="24"/>
          </template>
          下载防红短链列表
        </n-tag>
        <n-tag :bordered="false" class="text-base cursor-pointer bg-transparent hover:bg-[#F7F9FFFF]"
               @click="deleteLink">
          <template #avatar>
            <img :src="`${mainStore.commonImagePath}/icon_delete_download.svg`" alt="icon_delete_download" width="24"/>
          </template>
          删除
        </n-tag>
      </n-space>
    </template>
    <template #header-extra>
      <n-button size="large" type="primary" @click="linkState.showAddModal = true">
        <template #icon>
          <img :src="`${mainStore.commonImagePath}/link_union_btn.svg`" alt="link_union_btn">
        </template>
        生成短链
      </n-button>
    </template>
    <n-data-table :bordered="false" :columns="unref(antiRedTable.columns)" :data="antiRedTable.dataList"
                  :pagination="antiRedTable.dataList.length > 0 && unref(mainStore.pagination)"
                  :loading="antiRedTable.loading" :row-key="row => row.id" flex-height size="large"
                  @update:checked-row-keys="handleCheck">
      <template #empty>
        <n-space align="center" justify="center" vertical>
          <img :src="`${mainStore.commonImagePath}/empty_bg.svg`" alt="empty_bg">
          <n-text class="text-[#96A0B1]">暂无数据</n-text>
        </n-space>
      </template>
    </n-data-table>
  </n-card>

  <n-modal v-model:show="linkState.showAddModal" :auto-focus="false" :bordered="false" :show-icon="false"
           class="w-[480px]" preset="dialog" size="large" title="生成短链" to="#app">
    <n-form ref="addLinkFormRef" :model="linkState.addLinkForm" label-placement="left">
      <n-form-item>
        <n-input v-model:value="linkState.addLinkForm.url" :autosize="{minRows: 7, maxRows: 7}"
                 placeholder="请输入需要防红的网址，每行一个，支持http和https协议" type="textarea"/>
      </n-form-item>
      <n-form-item>
        <n-select v-model:value="linkState.addLinkForm.type" :options="antiRedOption" size="large"/>
      </n-form-item>
      <n-form-item label="请选择短网址：">
        <n-radio-group v-model:value="linkState.addLinkForm.short" name="short">
          <n-space>
            <n-radio value="Radio 1">Radio 1</n-radio>
            <n-radio value="Radio 2">Radio 2</n-radio>
            <n-radio value="Radio 3">Radio 3</n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
    </n-form>
    <n-space :size="16" justify="end">
      <n-button size="large" @click="linkState.showAddModal = false">取消</n-button>
      <n-button size="large" type="primary">确认</n-button>
    </n-space>
  </n-modal>

  <n-modal v-model:show="linkState.showModifyModal" :auto-focus="false" :bordered="false" :show-icon="false"
           class="w-[480px]" preset="dialog" size="large" title="编辑" to="#app">
    <n-form ref="modifyLinkFormRef" :model="linkState.modifyLinkForm" label-placement="left">
      <n-form-item>
        <n-input v-model:value="linkState.modifyLinkForm.url" placeholder="请输入需要防红的网址，支持http和https协议" size="large"/>
      </n-form-item>
      <n-form-item>
        <n-select v-model:value="linkState.modifyLinkForm.type" :options="antiRedOption" placeholder="请选择防红类型"
                  size="large"/>
      </n-form-item>
      <n-form-item>
        <n-tag :bordered="false" class="w-full pl-2" size="large" type="primary">https://weibo.com</n-tag>
      </n-form-item>
      <n-form-item>
        <n-input placeholder="请输入备注" size="large"></n-input>
      </n-form-item>
    </n-form>
    <n-space :size="16" justify="end">
      <n-button size="large" @click="linkState.showModifyModal = false">取消</n-button>
      <n-button size="large" type="primary">确认</n-button>
    </n-space>
  </n-modal>
</template>

<script setup>
import {reactive, unref, h, getCurrentInstance} from 'vue'
import {useRouter} from 'vue-router'
import {NA, NButton, NEllipsis, NInput, NSpace, NTag, NText} from 'naive-ui'
import {urlList, addUrl, modifyUrl, delUrl} from '@api/urlApi'
import {useApi} from '@/axios/tool/useRequest'
import {useDialog} from '@/hook/popup/dialog'
import {useMainStore} from '@/store'

const {proxy} = getCurrentInstance()
const router = useRouter()
const mainStore = useMainStore()
const currentPageImagePath = '/images/backstage-images/url-images'

const antiRedTable = reactive({
  columns: [
    {type: 'selection', fixed: 'left'},
    {
      title: '网址', key: 'url', fixed: 'left',
      render(row) {
        return h('div', {}, {
          default: () => [
            h(NEllipsis, {
              class: 'text-[rgba(0,0,0,0.9)]'
            }, {default: () => row.url}),
            h(NEllipsis, {
              class: 'text-[rgba(0,0,0,0.6)] text-xs'
            }, {default: () => `生成时间：${row.create_time}`})
          ]
        })
      }
    },
    {
      title: '备注', key: 'remarks',
      render(row) {
        return h(NInput, {
          placeholder: '请输入备注',
          bordered: false,
          value: row.remarks
        })
      }
    },
    {
      title: '防红短链', key: 'Domain',
      render(row) {
        return h(NA, {
          href: row.url,
          target: '_blank',
          class: 'text-base'
        }, {default: () => row.Domain})
      },
      ellipsis: {tooltip: true}
    },
    {
      width: 85,
      render(row) {
        return h(NSpace, {}, {
          default: () => [
            h(NButton, {
              text: true,
              disabled: antiRedTable.disabledBtn,
              onclick() {
              }
            }, {
              default: () => h('img', {
                src: `${currentPageImagePath}/link_qrcode_normal.svg`,
                alt: 'link_qrcode_normal',
              }),
            }),
            h(NButton, {
              text: true,
              disabled: antiRedTable.disabledBtn,
              onclick() {
                navigator.clipboard.writeText(row.Domain)
                $message.success('已成功复制到剪切板。')
              }
            }, {
              default: () => h('img', {
                src: `${currentPageImagePath}/link_copy_normal.svg`,
                alt: 'link_copy_normal',
                title: '复制'
              })
            })
          ]
        })
      }
    },
    {
      title: '类型', key: 'type',
      render(row) {
        return h(NTag, {
          type: row.type === 0 ? 'primary' : row.type === 1 ? 'success' : 'warning',
          size: 'large',
          bordered: false,
          class: 'px-6 rounded'
        }, {default: () => row.type === 0 ? '通用链接' : row.type === 1 ? '微信域名' : 'QQ专用'})
      }
    },
    {
      title: '访问次数', key: 'visit_num', width: 90,
      render(row) {
        return h(NText, {
          strong: true,
          class: 'text-[rgba(0,0,0,0.9)]'
        }, {default: () => row.visit_num})
      }
    },
    {
      title: '访问人数', key: 'visit_people', width: 90,
      render(row) {
        return h(NText, {
          strong: true,
          class: 'text-[rgba(0,0,0,0.9)]'
        }, {default: () => row.visit_people})
      }
    },
    {
      title: 'IP数', key: 'ip_num', width: 90,
      render(row) {
        return h(NText, {
          strong: true,
          class: 'text-[rgba(0,0,0,0.9)]'
        }, {default: () => row.ip_num})
      }
    },
    {
      title: '操作', fixed: 'right', width: 140,
      render(row) {
        return h(NSpace, {}, {
          default: () => [
            h(NButton, {
              text: true,
              disabled: antiRedTable.disabledBtn,
              title: '查看数据',
              onclick() {
                const routeData = router.resolve({path: `/statistics/${row.id}`})
                window.open(routeData.href, '_blank')
              }
            }, {
              default: () => h('img', {
                src: `${currentPageImagePath}/link_chart_normal.svg`,
                alt: 'link_chart_normal',
              })
            }),
            h(NButton, {
              text: true,
              disabled: antiRedTable.disabledBtn,
              title: '编辑',
              onclick() {
                linkState.showModifyModal = true
              }
            }, {
              default: () => h('img', {
                src: `${currentPageImagePath}/link_edit_normal.svg`,
                alt: 'link_edit_normal',
              })
            }),
            h(NButton, {
              text: true,
              disabled: antiRedTable.disabledBtn,
              title: '删除',
              onclick() {
                deleteLink()
              }
            }, {
              default: () => h('img', {
                src: `${mainStore.commonImagePath}/link_delete_normal.svg`,
                alt: 'link_delete_normal',
              })
            })
          ]
        })
      }
    },
  ],
  dataList: [],
  checkedRowKeys: [],
  disabledBtn: false,
  loading: false
})

const getUrlList = async () => {
  antiRedTable.dataList = []
  const {loading, result, request} = useApi(urlList())
  antiRedTable.loading = loading
  await request()
  console.log(result.value)
  if (result.value.code === 0) {
    antiRedTable.dataList = result.value.data
    console.log(antiRedTable.dataList)
  }
}
getUrlList()

const handleCheck = rowKeys => {
  antiRedTable.disabledBtn = rowKeys.length > 0
  antiRedTable.checkedRowKeys = rowKeys
}

const deleteLink = () => {
  useDialog({
    title: '删除',
    content: '删除防红短链后，所有数据也将会删除，是否删除？',
    confirm() {
    }
  })
}

const antiRedOption = [
  {label: '通用链接', value: 0},
  {label: '微信域名', value: 1},
  {label: 'QQ专用', value: 2},
]

const linkState = reactive({
  showAddModal: false,
  showModifyModal: false,
  addLinkForm: {
    url: '',
    type: 0
  },
  modifyLinkForm: {
    url: '',
    type: null
  }
})

const closeModal = formRef => {
  proxy.$refs[formRef].restoreValidation()
}
</script>

<style lang="less" scoped>
.antired-container {
  &:deep(.n-card-header) {
  }

  &:deep(.n-card__content) {
  }
}
</style>
